import { Button, Form, Input } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { login } from "@/api/user";

function LoginForm() {
  const navigate = useNavigate();
  // 成功
  const onFinish = async (values: { username: string; password: string }) => {
    /**
     * 1、token是用户的唯一标识
     * 2、登录时，后端生成的字符串，作为token,然后返回给前端
     * 3、前端存在cookies
     */
    const params = {
      username: "409019683@qq.com",
      password: "b0a5c59d95469ad94c1391e2575ca734a8b740eb",
      code: "513973",
    };
    // const data = await login(params);
    // 方式一
    // login(params)
    //   .then((response) => {
    //     console.log(response, "response");
    //   })
    //   .catch((error) => {
    //     console.log(error, "error");
    //   });
    // 409019683@qq.com
    // b0a5c59d95469ad94c1391e2575ca734a8b740eb
    // 513973
    // console.log(data, "data");

    console.log("Success:", values.username, values.password);
    // localStorage.setItem("token", "412656459568659");

    // 方式二
    try {
      const data = await login(params);
      // console.log(data, "login-data");
      // console.log(data.data.token);

      // 存储到本地 localStorage
      localStorage.setItem("token", data.data.token);
      navigate("/layout");
    } catch (error) {
      console.log(error);
    }
  };
  // 失败
  const onFinishFailed = (errorInfo: object) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Form
      name="basic"
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名!" }]}
      >
        <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[{ required: true, message: "请输入密码!" }]}
      >
        <Input.Password placeholder="请输入密码" prefix={<LockOutlined />} />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" block>
          登录
        </Button>
      </Form.Item>
    </Form>
  );
}

export default LoginForm;
